<template>
  <div class="app-container">
    <!-- 上部：串口通信区 -->
    <div class="top-section">
      <div class="serial-panel">
        <h1>电子秤</h1>
        <div class="control-group">
          <button @click="connectPort" :disabled="isConnected">连接串口</button>
          <button @click="disconnectPort" :disabled="!isConnected">断开连接</button>
          <div class="input-box">
            <input
              v-model="inputData"
              placeholder="输入发送内容"
              :disabled="!isConnected"
            />
            <button @click="sendData" :disabled="!isConnected">发送</button>
          </div>
        </div>
        <div class="data-display">
          <div class="action-buttons">
            <button @click="clearOutput">清空数据</button>
            <button 
              @click="saveData" 
              :disabled="!tableData.length"
              class="save-btn"
            >
              保存数据
            </button>
          </div>
          <pre>{{ outputData }}</pre>
        </div>
      </div>



        <div class="right-panel">
        <h2>数据表格</h2>
        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>数据内容</th>
              <th>时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td>{{ index + 1 }}</td>
              <td>{{ item.data }}</td>
              <td>{{ item.timestamp }}</td>
            </tr>
          </tbody>
        </table>
      </div>



      <div class="database-panel">
        <h2>数据库查询</h2>
        <div class="query-controls">
          <input v-model="queryKeyword" placeholder="输入查询关键词"/>
          <button @click="queryDatabase">查询</button>
          <button @click="clearQuery">重置</button>
        </div>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th v-for="col in dbColumns" :key="col">{{ col }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in dbData" :key="index">
                <td v-for="col in dbColumns" :key="col">{{ row[col] }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 下部：数据可视化区 -->
    <div class="chart-section">
      <h2>数据统计分析</h2>
      <div class="chart-controls">
        <select v-model="chartType">
          <option value="bar">柱状图</option>
          <option value="line">折线图</option>
          <option value="pie">饼图</option>
        </select>
        <button @click="generateChart">生成图表</button>
      </div>
      <div class="chart-container" ref="chartContainer"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import extend from "@/extension/bizappproject/app_wgjy/dianzicheng.jsx";
import { ref, defineComponent } from "vue";
export default {
  data() {
    return {
      // 串口通信数据
      port: null,
      isConnected: false,
      inputData: "",
      outputData: "",
      buffer: "",
      tableData: [],
      
      // 数据库查询数据
      queryKeyword: "",
      dbColumns: ["ID", "Content", "Timestamp"],
      dbData: [
        {ID: 1, Content: "示例数据1", Timestamp: "2024-05-20 10:00"},
        {ID: 2, Content: "示例数据2", Timestamp: "2024-05-20 11:00"}
      ],
      
      // 图表数据
      chartType: "bar",
      chartInstance: null,
      chartData: {
        categories: ["数据1", "数据2", "数据3"],
        values: [12, 19, 8]
      }
    };
  },

  methods: {
    // 串口通信方法
    async connectPort() {
      if (!("serial" in navigator)) {
        alert("浏览器不支持Web Serial API");
        return;
      }
      try {
        this.port = await navigator.serial.requestPort();
        await this.port.open({ baudRate: 9600 });
        this.isConnected = true;
        this.readData();
      } catch (error) {
        alert("连接失败: " + error.message);
      }
    },

    async readData() {
      try {
        const reader = this.port.readable.getReader();
        const decoder = new TextDecoder();
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          
          this.buffer += decoder.decode(value, { stream: true });
          const lines = this.buffer.split("\n");
          
          if (lines.length > 1) {
            for (let i = 0; i < lines.length - 1; i++) {
              const data = lines[i].trim();
              if (data) {
                this.outputData += data + "\n";
                this.tableData.push({
                  content: data,
                  timestamp: new Date().toLocaleString()
                });
                this.updateChartData(data);
              }
            }
            this.buffer = lines[lines.length - 1];
          }
        }
      } catch (error) {
        console.error("读取错误:", error);
      }
    },

    updateChartData(data) {
      // 简单示例：按数据长度统计
      const index = Math.min(Math.floor(data.length / 5), 2);
      this.chartData.values[index]++;
      if (this.chartInstance) {
        this.generateChart();
      }
    },

    // 数据库方法
    queryDatabase() {
      // 模拟数据库查询
      this.dbData = this.queryKeyword 
        ? this.dbData.filter(item => 
            item.Content.includes(this.queryKeyword))
        : this.getSampleData();
    },

    getSampleData() {
      return [
        {ID: 1, Content: "示例数据1", Timestamp: "2024-05-20 10:00"},
        {ID: 2, Content: "示例数据2", Timestamp: "2024-05-20 11:00"},
        {ID: 3, Content: "测试数据", Timestamp: "2024-05-20 12:00"}
      ];
    },

    // 图表方法
    generateChart() {
      if (!this.chartInstance) {
        this.chartInstance = echarts.init(this.$refs.chartContainer);
      }
      
      const option = {
        title: { text: "串口数据统计" },
        tooltip: {},
        xAxis: { data: this.chartData.categories },
        yAxis: {},
        series: [{
          name: "数量",
          type: this.chartType,
          data: this.chartData.values,
          itemStyle: {
            color: '#5470C6'
          }
        }]
      };
      
      this.chartInstance.setOption(option);
      window.addEventListener('resize', this.chartInstance.resize);
    },

    // 通用方法
    saveData() {
      const blob = new Blob([JSON.stringify(this.tableData, null, 2)], 
        { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `serial-data-${new Date().toISOString().slice(0,10)}.json`;
      a.click();
      URL.revokeObjectURL(url);
    },

    clearOutput() {
      this.outputData = "";
      this.tableData = [];
      this.chartData.values = [0, 0, 0];
      if (this.chartInstance) {
        this.generateChart();
      }
    }
  },

  mounted() {
    this.generateChart();
  },

  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
};
</script>

<style>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  background: #f5f7fa;
}

.top-section {
  display: flex;
  gap: 20px;
  height: 50%;
  margin-bottom: 20px;
}

.serial-panel, .database-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

.serial-panel {
  flex: 1; /* 左侧面板占据剩余空间 */
  padding-right: 20px; /* 右侧留出间距 */
  border-right: 1px solid #ccc; /* 添加分割线 */
}

.right-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  flex: 1; /* 右侧面板占据剩余空间 */
  padding-left: 20px; /* 左侧留出间距 */
  border-right: 1px solid #ccc; /* 添加分割线 */
}
.database-panel {
  flex: 1; /* 右侧面板占据剩余空间 */
  padding-left: 20px; /* 左侧留出间距 */
}

.chart-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

h1, h2 {
  color: #333;
  margin-bottom: 15px;
}

.control-group, .query-controls, .chart-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.input-box {
  display: flex;
  flex: 1;
  gap: 10px;
}

input, select {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  background: #409EFF;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
}

button:hover {
  background: #66b1ff;
}

button:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.save-btn {
  background: #67C23A;
}

.save-btn:hover {
  background: #85ce61;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.data-display pre {
  background: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  height: 150px;
  overflow: auto;
  font-family: monospace;
}

.table-container {
  flex: 1;
  overflow: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  border: 1px solid #ebeef5;
  text-align: left;
}

th {
  background: #f5f7fa;
  position: sticky;
  top: 0;
}

tr:hover {
  background: #f5f7fa;
}

.chart-container {
  width: 100%;
  height: calc(100% - 60px);
  min-height: 300px;
}
</style>